package tool

import (
	"bytes"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"

	"unsafe"
)

//post 请求
func DingPostRequest(song map[string]interface{}, urlRoute string) (map[string]interface{}, error) {

	var res map[string]interface{}
	bytesData, err := json.Marshal(song)
	if err != nil {
		logs.Error(err)
		return res, err
	}
	reader := bytes.NewReader(bytesData)
	url := "https://oapi.dingtalk.com" + urlRoute
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		logs.Error(err)
		return res, err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		logs.Error(err)
		return res, err
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error(err)
		return res, err
	}
	//byte数组直接转成string，优化内存
	str := (*string)(unsafe.Pointer(&respBytes))

	err = json.Unmarshal([]byte(*str), &res)
	if err != nil {
		logs.Error(*str)
		logs.Error(err)
		return res, err
	}
	return res, err
}
